<template>
  <div>
    <table>
      <thead>
        <tr>
          <th v-for="(item,index) in gridColumns" :key="index">
            {{item.name}}
            <span class="arrow" v-show="item.hasOwnProperty('isAsc')" :class="item.isAsc?'asc':'dsc'" @click="sortFn(item)">
            </span>
          </th>
        </tr>
      </thead>
      <tbody>
        <tr v-for="(item,index) in newList" :key="index">
          <td v-for="(i,v) in gridColumns" :key="v">
            {{item[i.name]}}
          </td>
        </tr>
      </tbody>
    </table>
  </div>
</template>

<script>
export default {
  props: ['gridData', 'gridColumns', 'val'],
  methods: {
    sortFn (item) {
      if (!item.hasOwnProperty('isAsc')) {
        return
      } else {
        item.isAsc = !item.isAsc
      }
      // console.log(typeof this.gridData[0][item.name])
      if (typeof this.gridData[0][item.name] == 'string') {
        if (item.isAsc) {
          this.gridData.sort((v, i) => {
            if (v[item.name] > i[item.name]) {
              return 1
            } else if (v[item.name] < i[item.name]) {
              return -1
            } else {
              return 0
            }
          })
        } else {
          this.gridData.reverse()
        }
      }
      if (typeof this.gridData[0][item.name] == 'number') {
        if (item.isAsc) {
          this.gridData.sort((v, i) => {
            return v[item.name] - i[item.name]
          })
        } else {
          this.gridData.reverse()
        }
      }
    }
  },
  computed: {
    newList () {
      if (!this.val) {
        return this.gridData
      } else {
        return this.gridData.filter(val => {
          return val.name.toUpperCase().indexOf(this.val.toUpperCase()) != -1
        })
      }
    }
  }
}
</script>

<style scoped>
</style>